package com.apes.fn.scm.retailOrder.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.pi.model.Timestamp;
import com.apes.pi.repository.TimestampRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @program: apes-server
 * @description: 日结报表
 * @author: czs
 * @create: 2023-02-28 09:47
 **/
@Service("daliyReportService")
public class DaliyReportService extends DomainService {

    @Autowired
    TimestampRepository timestampRepository;
    @Autowired
    private EntityManager entityManager;

    /**
     * 日结汇总总入口
     * @param request
     * @return
     * @throws Exception
     */
    public int execSumReport(SimpleRequest request) throws Exception {
        JSONObject jo = request.getJO();
        String type = jo.getString("Type");
        if (type == null) {
            throw new RuntimeException("汇总错误,未知类型");
        }
        Integer delaySecond = jo.getInteger("delaySecond");
        if (delaySecond == null) delaySecond = 5;
        switch (type) {
            case "salesProduct":
                return execSumReportProcess(delaySecond, "SumDailysalesreportProduct", "{call SUM_DAILYSALESREPORT_PRODUCT(?,?)}");
            case "salesOrder":
                return execSumReportProcess(delaySecond, "SumDailysalesreportOrder", "{call SUM_DAILYSALESREPORT_ORDER(?,?)}");
            case "salesPayment":
                return execSumReportProcess(delaySecond, "SumDailysalesreportPayment", "{call SUM_DAILYSALESREPORT_PAYMENT(?,?)}");
            case "cost":
                return execSumReportProcess(delaySecond, "sumCostReport", "{call SUM_RCL_COST_REPORT(?,?)}");
            case "salse":
                execSumReportProcess("{call SUM_RCL_SALES_CALL(?)}");
                execSumReportProcess("{call SUM_RCL_CATEGORY_CALL(?)}");
                return 1;
            case "times":
                return execSumTimesReport();
            default:
                throw new RuntimeException("汇总错误,未知类型");
        }
    }

    /**
     * 获取不带时间点的当前日期，返回JAVA类型变量
     *
     * @return
     */
    private Date getNowDate() throws ParseException {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date);

        if (dateString.indexOf(" ") >= 0) {
            dateString = dateString.substring(0, dateString.indexOf(" ")).trim();
        }
        String DateList[] = dateString.split("-");
        String strMM = String.format("%02d", Integer.parseInt(DateList[1]));
        String strDD = String.format("%02d", Integer.parseInt(DateList[2]));
        String strDate = DateList[0] + '-' + strMM + '-' + strDD;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return (Date) sdf.parse(strDate);
    }

    /**
     * 底表数据加工成因营业额报表
     * @return
     * @throws Exception
     */
    private int execSumReportProcess(String callName) throws Exception {
        EntityManager entityManager = SpringManager.getBean(EntityManager.class);
        Query query = entityManager.createNativeQuery(callName).setParameter(1, getNowDate());
        return query.executeUpdate();
    }

    /**
     * 计算台次报表
     * @return
     * @throws Exception
     */
    private int execSumTimesReport() throws Exception {
        EntityManager entityManager = SpringManager.getBean(EntityManager.class);
        Query query = entityManager.createNativeQuery("{call SUM_SALES_TIMES_BUSINESS(?)}").setParameter(1, getNowDate());
        return query.executeUpdate();
    }

    private int execSumReportProcess(Integer delaySecond,String timestampName,String callName) throws Exception {
        Date newDate = new Date();
        Date lastDate = daliyReportGetLastDateAndUpdateTime(delaySecond, newDate,timestampName);
        Query query = entityManager.createNativeQuery(callName)
                .setParameter(1, lastDate)
                .setParameter(2, newDate);
        return query.executeUpdate();
    }


    private Date daliyReportGetLastDateAndUpdateTime(Integer delaySecond, Date newDate, String timestampName) throws Exception {
        Timestamp timestamp = timestampRepository.findOne(timestampName);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        if (timestamp==null){
            timestamp = new Timestamp();
            Date nowDate = getNowDate();
            String format = sdf.format(nowDate);
            timestamp.setId(timestampName);
            timestamp.setTime(format);
            timestamp.setType("timestamp");
        }
        Date lastDate = sdf.parse(timestamp.getTime());

        newDate.setTime(new Date().getTime()-(delaySecond*1000));

        String newDateSTR = sdf.format(newDate);
        timestamp.setTime(newDateSTR);
        timestampRepository.saveAndFlush(timestamp);
        return lastDate;
    }

    /**
     * 日结前天数据
     * @param request
     */
    public void fullSumReportDaliy(SimpleRequest request) throws Exception {
        Date newDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dayTime = sdf.parse(sdf.format(newDate));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dayTime);
        calendar.add(Calendar.DATE,-1);
        Date startTime = calendar.getTime();

        EntityManager entityManager = SpringManager.getBean(EntityManager.class);

        Query query = entityManager.createNativeQuery("{call SUM_FULL_RCL_REPORT(?,?)}")
                .setParameter(1,startTime)
                .setParameter(2,dayTime);
        query.executeUpdate();
    }
}
